import { reactive, ref, watch } from 'vue';
// import { uni } from '@dcloudio/uni-app';
import { request } from '@/utils/request'
import { h5CalculateMd5, h5Upload } from "@/components/upload/utils";
const token = 'pat_hDLUMqRTuu6iyZo25QTCKqK07KkRwh6JiQiroJZSUqdKlDnwrMF6PE1LI5POPB70'; //2025/3/1过期
// const workflow_id = '7466775571867959346';
const url = `https://api.coze.cn/v1/workflow/run`;
const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
};

export function useResource(baseUrl) {
    const pageData = reactive({
        page: 1,
        size: 30,
        total: 0,
    });
    const resources = ref([]);

    const fetchPageResources = (n) => {
        resources.value = [];
        pageData.page = n;
        fetchResources();
    }

    const fetchResources = async () => {
        try {
            const response = await uni.request({
                url: `${baseUrl}?page=${pageData.page}&limit=${pageData.size}`,
                method: 'GET'
            });
            pageData.total = response.data.data.total
            resources.value = response.data.data.resources
            // resources.value = isRefresh ? response.data.data.resources : [...resources.value, ...response.data.data.resources];
        } catch (error) {
            console.error('Failed to fetch resources:', error);
        }
    };

    const deleteResource = async (md5, isRefresh = true) => {
        await uni.request({
            url: `${baseUrl}/${md5}`,
            method: 'DELETE'
        });
        isRefresh && fetchResources(); // 刷新列表
    };


    const findByMd5 = async (md5) => {
        try {
            const response = await uni.request({
                url: `${baseUrl}/${md5}`,
                method: 'GET'
            });
            return response.data?.data?.path ? response.data.data : null;
        } catch (error) {
            console.error("Failed to fetch resource by MD5:", error);
        }
        return null;
    }

    function uploadResource(filePath, md5) {
        uni.uploadFile({
            url: `${baseUrl}/upload`,
            filePath,
            name: 'file',
            formData: { 'md5': md5 },
            success: (uploadRes) => {
                const rs = JSON.parse(uploadRes.data);
                if (rs.data) {
                    resources.value.unshift(rs.data);
                } else {
                    uni.showToast({ title: '上传失败', icon: 'none' });
                }
            }
        });
    }

    function h5UploadResource(file, md5) {
        h5Upload(`${baseUrl}/upload`, file, md5).then((res) => {
            console.log('H5 upload success:', res);
            if (res.data) {
                uni.showToast({ title: '上传成功', icon: 'success' });
                uni.hideLoading();
                resources.value.unshift(res.data);
            } else {
                uni.showToast({ title: '上传失败', icon: 'none' });
            }
        }).catch((err) => {
            console.error('H5 upload error:', err);
            uni.showToast({ title: '上传失败', icon: 'none' });
        })
    }

    async function h5UploadBase64(dataurl) {
        const file = dataURLtoFile(dataurl, 'image.png'); // 将base64转换为文件对象
        console.log('file ==', file);
        const md5 = await h5CalculateMd5(file);
        console.log('md5 ==', md5);
        h5UploadResource(file, {md5});
    }

    function dataURLtoFile(dataurl, filename) {
        const arr = dataurl.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
    }


    return {
        h5UploadBase64,
        pageData,
        resources,
        findByMd5,
        fetchResources,
        deleteResource,
        uploadResource,
        h5UploadResource,
        fetchPageResources
    };
}